package com.lbc.service.impl;

import com.lbc.bean.entity.KidAssist;
import com.lbc.bean.entity.Organization;
import com.lbc.bean.entity.User;
import com.lbc.bean.vo.KidAssistVO;
import com.lbc.common.constants.Constants;
import com.lbc.common.exception.CustomException;
import com.lbc.common.utils.JwtUtils;
import com.lbc.dao.custom.CtKidAssistMapper;
import com.lbc.dao.custom.CtOrganizationMapper;
import com.lbc.service.KidAssistService;
import com.lbc.service.KidService;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * @author xyl
 * @date 2021-03-29 17:44
 */
@Service
public class KidAssistServiceImpl implements KidAssistService {
    @Autowired
    private CtKidAssistMapper kidAssistMapper;
    @Autowired
    private KidService kidService;
    @Autowired
    private CtOrganizationMapper organizationMapper;

    @Override
    public KidAssist getByKidIdAndUserId(Integer userId, Integer kidId) {
        return kidAssistMapper.selectByUserIdAndKidId(userId, kidId);
    }

    @Override
    public int assist(Integer assistTo) {
        Organization organization = organizationMapper.selectByUserId(JwtUtils.getUserId());
        KidAssist kidAssist = kidAssistMapper.selectByOrgIdAndKidId(organization.getOrganizationId(), assistTo);
        if(ObjectUtils.isNotEmpty(kidAssist)){
            CustomException.cast("此儿童已被 该机构帮扶！");
        }
        KidAssist ka = new KidAssist();
        ka.setAssistTo(assistTo);
        ka.setAssistBy(organization.getOrganizationId());
        ka.setCreateTime(new Date());
        return kidAssistMapper.insert(ka);
    }

    @Override
    public List<KidAssistVO> list(Integer orgId) {
        Integer userId = null;
        User user = (User) SecurityUtils.getSubject().getPrincipal();
        if (Constants.ROLE_ORGANIZATION == user.getRoleId()) {
            Organization organization = organizationMapper.selectByUserId(user.getUserId());
            userId = organization.getOrganizationId();
        }else if(Constants.ROLE_ADMIN == user.getRoleId()){
            userId = orgId;
        }
        List<KidAssistVO> kidAssistVOS = kidAssistMapper.selectListVO(userId);
        kidAssistVOS.forEach(kid -> {
            kid.setVo(kidService.get(kid.getAssistTo()));
        });
        return kidAssistVOS;
    }
}
